package dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import pojo.AdSpace;
import pojo.AdSpaceStatusEnum;
import dao.AdSpaceDao;
import dto.AdSpaceDto;

@Repository(value="adSpaceDao")
public class AdSpaceDaoImpl implements AdSpaceDao{

	@PersistenceContext(name="un")
	private EntityManager manager;
	
	@Override
	public AdSpace add(AdSpace t) {
		manager.persist(t);
		return t;
	}

	@Override
	public AdSpace delete(String id) {
		return null;
	}

	@Override
	public AdSpace update(AdSpace t) {
		System.out.println(t.toString()+"......");
		System.out.println("id..."+t.getId());
		AdSpace adSpace = manager.find(AdSpace.class, t.getId());
		System.out.println("up...."+adSpace.toString());
		if (adSpace!=null && "audit".equals(adSpace.getStatus())) {
			//adSpace.setImgPath(t.getImgPath());
			adSpace.setAdPrice(t.getAdPrice());
			adSpace.setFoodId(t.getFoodId());
			adSpace.setStartTime(t.getStartTime());
			adSpace.setEndTime(t.getEndTime());
			adSpace.setStatus(t.getStatus());
			return manager.merge(adSpace);
		}
		return null;
	}

	@Override
	public AdSpace load(String id) {
		String jpql = "SELECT a FROM AdSpace a WHERE a.id=:id";
		List<AdSpace> adSpaces = manager.createQuery(jpql)
				.setParameter("id", id)
				.getResultList();
		if(adSpaces.size() > 0)
			return adSpaces.get(0);
		return null;
	}

	@Override
	public List<AdSpace> findAll() {
		return null;
	}

	@Override
	public List<AdSpace> getByStatus(String status) {
		String jpql = "SELECT a FROM AdSpace a WHERE a.status=:status";
		List<AdSpace> adSpaces = manager.createQuery(jpql)
				.setParameter("status", status)
				.getResultList();
		return adSpaces;
	}

	@Override
	public AdSpaceDto addAds(AdSpaceDto adSpace) {
		manager.persist(adSpace);
		return adSpace;
	}

	@Override
	public List<AdSpace> getByTimeStamp(Date startTime, String status) {
		String jpql = "SELECT a FROM AdSpace a WHERE a.startTime=:startTime AND a.status=:status";
		List<AdSpace> adSpaces = manager.createQuery(jpql)
				.setParameter("startTime", startTime)
				.setParameter("status", status)
				.getResultList();
		return adSpaces;
	}

	@Override
	public List<AdSpace> getAdsInOneTime(Date time, String status) {
		String jpql = "SELECT a FROM AdSpace a WHERE a.startTime<:time1 AND a.endTime>:time2 AND a.status=:status";
		List<AdSpace> adSpaces = manager.createQuery(jpql)
				.setParameter("time1", time)
				.setParameter("time2", time)
				.setParameter("status", status)
				.getResultList();
		return adSpaces;
	}

}
